<script setup>
import HeadComponents from "@/components/headComponents.vue";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import http from "@/utils/http";

// 翻译历史记录
const translationHistory = ref([]);
const loading = ref(false);

// 从后端加载翻译历史
const loadTranslationHistory = async () => {
  loading.value = true;
  try {
    const response = await http.get('/history/');
    translationHistory.value = response.data;
  } catch (error) {
    console.error('加载翻译历史失败:', error);
    ElMessage.error('加载翻译历史失败');
  } finally {
    loading.value = false;
  }
};

// 清空翻译历史
const clearTranslationHistory = async () => {
  try {
    await http.delete('/history/');
    translationHistory.value = [];
    ElMessage.success('翻译历史已清空');
  } catch (error) {
    console.error('清空翻译历史失败:', error);
    ElMessage.error('清空翻译历史失败');
  }
};

onMounted(() => {
  loadTranslationHistory();
});
</script>

<template>
  <head-components></head-components>
  <div class="container">
    <div class="card">
      <h3>历史搜索记录</h3>

      <!-- 翻译历史列表 -->
      <div v-if="loading" class="loading">加载中...</div>
      <ul class="history-list" v-else-if="translationHistory.length">
        <li v-for="record in translationHistory" :key="record.id" class="history-item">
          <p><strong>时间：</strong>{{ new Date(record.created_at).toLocaleString() }}</p>
          <p><strong>原文：</strong>{{ record.source_text }}</p>
          <p><strong>译文：</strong>{{ record.translated_text }}</p>
          <p><small>{{ record.source_lang }} → {{ record.target_lang }}</small></p>
        </li>
      </ul>

      <p v-else-if="!loading">暂无翻译记录</p>

      <button class="btn btn-secondary" @click="clearTranslationHistory" :disabled="loading">清空翻译记录</button>
    </div>
  </div>
</template>

<style>
@import '@/assets/base.css';
.container {
  flex: 1;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  position: relative;
}
</style>
<style scoped>
.history-list {
  list-style-type: none;
  padding-left: 0;
}

.history-item {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  padding: 1rem;
  margin-bottom: 0.5rem;
  border-radius: 6px;
}
</style>